﻿using ModuleBase.googoltech.GTS;
using ModuleBase;
using Prism.Ioc;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog.Targets;

namespace AxisMovePoint
{
    public class AxisMovePoint : ModuleBase.ModuleBase
    {
        private IAxisCardService _axisCardService;
        private ModuleStateService _moduleStateService;
        bool outputs = false;
        bool isExecuted = false;
        private IContainerProvider _containerProvider;

        private int _parameter1 = 1;
        public int Parameter1
        {
            get => _parameter1;
            set
            {
                if (_parameter1 != value)
                {
                    _parameter1 = value;
                    OnPropertyChanged(nameof(Parameter1));
                }
            }
        }

        private double _parameter2;
        public double Parameter2
        {
            get => _parameter2;
            set
            {
                if (_parameter2 != value)
                {
                    _parameter2 = value;
                    OnPropertyChanged(nameof(Parameter2));
                }
            }
        }

        private string _parameter3;
        public string Parameter3
        {
            get => _parameter3;
            set
            {
                if (_parameter3 != value)
                {
                    _parameter3 = value;
                    OnPropertyChanged(nameof(Parameter3));
                }
            }
        }

        private int _parameter4 = 0;
        public int Parameter4
        {
            get => _parameter4;
            set
            {
                if (_parameter4 != value)
                {
                    _parameter4 = value;
                    OnPropertyChanged(nameof(Parameter4));
                }
            }
        }
        private string _parameter5 = "Top_A8";
        public string Parameter5
        {
            get => _parameter5;
            set
            {
                if (_parameter5 != value)
                {
                    _parameter5 = value;
                    OnPropertyChanged(nameof(Parameter5));
                }
            }
        }
        private string _parameter6 = "X";
        public string Parameter6
        {
            get => _parameter6;
            set
            {
                if (_parameter6 != value)
                {
                    _parameter6 = value;
                    OnPropertyChanged(nameof(Parameter6));
                }
            }
        }
        public override Dictionary<string, object> GetProperties()
        {
            return new Dictionary<string, object>
            {
                { "轴号", Parameter1 },
                { "速度", Parameter2 },
                { "点位名称", Parameter3 },
                { "点位所属轴", Parameter6 },
                { "HandIndex", Parameter4 },
                { "轴卡参数名", Parameter5 },
            };
        }

        public override Dictionary<string, List<object>> PropertyOptions { get; } = new Dictionary<string, List<object>>
        {
            { "轴号", new List<object>{ 1,2,3,4,5,6,7,8 } },
            { "HandIndex", new List<object>{ 0,1,2,3,4,5,6,7,8 } },
            { "点位所属轴", new List<object>{ "X", "Y","Z","R" } }
        };

        public AxisMovePoint(IContainerProvider containerProvider, ModuleStateService moduleStateService)
        {
            _containerProvider = containerProvider;
            _moduleStateService = moduleStateService;
            _moduleStateService.RegisterModule(Id);
            Name = "轴点位移动";

            DisplayNameToPropertyNameMap = new Dictionary<string, string>
            {
                { "轴号", nameof(Parameter1) },
                { "速度", nameof(Parameter2) },
                { "点位名称", nameof(Parameter3) },
                { "点位所属轴", nameof(Parameter6) },
                { "HandIndex", nameof(Parameter4) },
                { "轴卡参数名", nameof(Parameter5) }
            };
        }

        public override bool Execute()
        {
            Status = ModuleBase.ModuleStatus.Executing; // 设置状态为执行中

            _axisCardService = _containerProvider.Resolve<IAxisCardService>(Parameter5);
            AxisParm _axis = GetAxisByNumber(Parameter1);
            var position = 0.0;

            try
            {
                using var mdb = _containerProvider.Resolve<MDbContext>();
                var _mParam = mdb.MParams.FirstOrDefault(x => x.Name == Parameter3 && x.Hand == Parameter4);
                if (_mParam != null)
                {
                    var _point = JsonConvert.DeserializeObject<MPoint>(_mParam.Value);
                    if (Parameter6.ToString() == "Y")
                    {
                        position = _point.Y;
                    }
                    else if (Parameter6.ToString() == "Z")
                    {
                        position = _point.Z;
                    }
                    else if (Parameter6.ToString() == "R")
                    {
                        position = _point.R;
                    }
                    else if (Parameter6.ToString() == "X")
                    {
                        position = _point.X;
                    }
                    int stepnum = 0;
                    Stopwatch sw = Stopwatch.StartNew();
                    while (true)
                    {
                        if (_moduleStateService.IsStopped)
                        {
                            GTSCard.AxisStop(_axis, 0);
                            outputs = false;
                            return outputs;
                        }
                        switch (stepnum)
                        {
                            case 0:
                                {
                                    GTSCard.AxisPosMove(ref _axis, position, Parameter2);
                                    MyFunc.AddMessage($"{Parameter6}轴{_axis.AxisId}开始移动，目标位置：{position}");
                                    stepnum = 1;
                                }
                                break;
                            case 1:
                                if (GTSCard.AxisPosMoveCheckDone(_axis))
                                {
                                    MyFunc.AddMessage($"{Parameter6}轴{_axis.AxisId}已到目标位置：{position}");
                                    stepnum = 2;
                                }
                                break;
                            case 2:
                                if (sw.Elapsed.TotalSeconds > 0.5)
                                {
                                    sw.Stop();
                                    outputs = true;
                                    isExecuted = true;
                                    return outputs;
                                }
                                break;
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                }
                else
                {
                    outputs = false;
                }
            }
            catch (Exception exp)
            {
                Debug.WriteLine($"模块[{Name}]执行异常：" + exp.ToString());
                outputs = false;
            }
            return outputs;
        }

        public override async Task<bool> ExecuteAsync()
        {
            outputs = false;
            var result = await Task.Run(() => Execute());
            return result;
        }

        public override void Initialize()
        {
            isExecuted = false;
        }
        private AxisParm GetAxisByNumber(int axisNumber)
        {
            switch (axisNumber)
            {
                case 1: return _axisCardService.A1;
                case 2: return _axisCardService.A2;
                case 3: return _axisCardService.A3;
                case 4: return _axisCardService.A4;
                case 5: return _axisCardService.A5;
                case 6: return _axisCardService.A6;
                case 7: return _axisCardService.A7;
                case 8: return _axisCardService.A8;
                default: return _axisCardService.A1;
            }
        }

        public override string Description => "轴点位移动模块：根据点位名称和所属轴，实现指定轴的精准点位移动。";
    }
}